package interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import config.Consts;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by BaiYunfei on 2017/6/15.
 */
public class LoginInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {
        Controller controller = invocation.getController();
        HttpServletRequest request = controller.getRequest();

        controller.setAttr("baseUrl",request.getContextPath());
        controller.setAttr("assetsUrl", request.getContextPath()+"/assets");
        controller.setAttr("role", controller.getSession().getAttribute(Consts.SESSION_USER_ROLE));
        controller.setAttr("userId", controller.getSession().getAttribute(Consts.SESSION_USER_ID));

        if(request.getSession().getAttribute(Consts.SESSION_USER_ID) != null){
            invocation.invoke();
            return;
        }
        if(invocation.getActionKey().startsWith("/login")){
            invocation.invoke();
            return;
        }
        controller.redirect("/loginPage");
    }
}
